//
//  XiaoximenBasicInfoViewController.m
//  Xiaoximaen_iOS
//
//  Created by Wang Zhongyu on 12-7-17.
//  Copyright (c) 2012年 Peking University. All rights reserved.
//

#import "XiaoximenBasicInfoViewController.h"
#import "XiaoximenSelectPersonViewController.h"
#import "KalDate.h"

@interface XiaoximenBasicInfoViewController () {
    BOOL _isKeyboardHidden;
	CGRect initScrollFrame;
}

@end

@implementation XiaoximenBasicInfoViewController
@synthesize scrollView;
@synthesize contentTextField;
@synthesize addMorePlaceButton;
@synthesize textFields = _textFields;
@synthesize deleteButtons = _deleteButtons;

- (NSArray *)textFields
{
	if (_textFields == nil) {
		_textFields = [[NSMutableArray alloc] init];
	}
	return _textFields;
}
- (NSArray *)deleteButtons
{
	if (_deleteButtons == nil) {
		_deleteButtons = [[NSMutableArray alloc] init];
	}
	return _deleteButtons;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	[self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"bar"] forBarMetrics:UIBarMetricsDefault];
	self.scrollView.contentSize = CGSizeMake(320, 416);
	initScrollFrame = self.scrollView.frame;
	initScrollFrame.origin.y = initScrollFrame.origin.y - 44;
	
	UIView *contentPaddingView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 18, 0)];
	contentTextField.leftView = contentPaddingView;
	contentTextField.leftViewMode = UITextFieldViewModeAlways;	
	[self.contentTextField becomeFirstResponder];
}

- (void)viewDidUnload
{
	[self setScrollView:nil];
	[self setContentTextField:nil];
	[self setAddMorePlaceButton:nil];
    [super viewDidUnload];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (void)viewWillAppear:(BOOL)animated {
    // Register notifications for when the keyboard appears 
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
}

- (void)viewWillDisappear:(BOOL)animated {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)addPlaceTextField
{
	UITextField *nextTextField = [[UITextField alloc] initWithFrame:CGRectMake(addMorePlaceButton.frame.origin.x, addMorePlaceButton.frame.origin.y, addMorePlaceButton.frame.size.width, addMorePlaceButton.frame.size.height)];
	nextTextField.placeholder = @"输入地点选项";
	nextTextField.background = [UIImage imageNamed:@"text"];
	nextTextField.returnKeyType = UIReturnKeyNext;
	nextTextField.borderStyle = UITextBorderStyleNone;
	nextTextField.enablesReturnKeyAutomatically = YES;
	nextTextField.autocorrectionType = UITextAutocorrectionTypeNo;
	nextTextField.delegate = self;
	UIView *nextPaddingView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 18, 0)];
	nextTextField.leftView = nextPaddingView;
	nextTextField.leftViewMode = UITextFieldViewModeAlways;
	nextTextField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
	
	[self.scrollView addSubview:nextTextField];
	[self.textFields addObject:nextTextField];
	
	[addMorePlaceButton setFrame:CGRectMake(addMorePlaceButton.frame.origin.x, addMorePlaceButton.frame.origin.y+addMorePlaceButton.frame.size.height+8, addMorePlaceButton.frame.size.width, addMorePlaceButton.frame.size.height)];
	if (self.addMorePlaceButton.frame.origin.y + self.addMorePlaceButton.frame.size.height > self.scrollView.contentSize.height - 20) {
		self.scrollView.contentSize = CGSizeMake(self.scrollView.contentSize.width, self.addMorePlaceButton.frame.origin.y + self.addMorePlaceButton.frame.size.height + 20);
	}
	
	[nextTextField becomeFirstResponder];
}
- (void)completeTextField:(UITextField *)textField
{
	[textField setBackground:[UIImage imageNamed:@"textfield"]];
	[textField setPlaceholder:@""];
	[textField setEnabled:NO];
	
	UIButton *deleteButton = [[UIButton alloc] initWithFrame:CGRectMake(textField.frame.origin.x+textField.frame.size.width-30, textField.frame.origin.y+10, 20, 20)];
	[deleteButton setBackgroundImage:[UIImage imageNamed:@"del_normal"] forState:UIControlStateNormal];
	[deleteButton setBackgroundImage:[UIImage imageNamed:@"del_pressed"] forState:UIControlStateHighlighted];
	[deleteButton addTarget:self action:@selector(deleteTextField:) forControlEvents:UIControlEventTouchUpInside];
	[self.scrollView addSubview:deleteButton];
	[self.deleteButtons addObject:deleteButton];
}
- (void)deleteTextField:(id)sender
{
	[self deleteTextFieldAtIndex:[self.deleteButtons indexOfObject:sender]];
}
- (void)deleteTextFieldAtIndex:(NSUInteger)index
{
	[[self.textFields objectAtIndex:index] removeFromSuperview];
	[[self.deleteButtons objectAtIndex:index] removeFromSuperview];
	
	for (NSUInteger i = index+1; i < self.textFields.count; i++) {
		UITextField *adjustTextField = [self.textFields objectAtIndex:i];
		adjustTextField.frame = CGRectMake(adjustTextField.frame.origin.x, adjustTextField.frame.origin.y - 48, adjustTextField.frame.size.width, adjustTextField.frame.size.height);
		if (i < self.deleteButtons.count) {
			UIButton *adjustButton = [self.deleteButtons objectAtIndex:i];
			adjustButton.frame = CGRectMake(adjustButton.frame.origin.x, adjustButton.frame.origin.y - 48, adjustButton.frame.size.width, adjustButton.frame.size.height);
		}
	}
	self.addMorePlaceButton.frame = CGRectMake(self.addMorePlaceButton.frame.origin.x, self.addMorePlaceButton.frame.origin.y - 48, self.addMorePlaceButton.frame.size.width, self.addMorePlaceButton.frame.size.height);
	
	if (self.addMorePlaceButton.frame.origin.y + self.addMorePlaceButton.frame.size.height < self.scrollView.contentSize.height - 20 && self.scrollView.contentSize.height > 416) {
		self.scrollView.contentSize = CGSizeMake(self.scrollView.contentSize.width, self.addMorePlaceButton.frame.origin.y + self.addMorePlaceButton.frame.size.height + 20 > 416 ? self.addMorePlaceButton.frame.origin.y + self.addMorePlaceButton.frame.size.height + 20 : 416);
	}
}

- (void)keyboardWillShow:(NSNotification*)notification {
	_isKeyboardHidden = NO;
    [self moveViewForKeyboard:notification up:YES];
}

- (void)keyboardWillHide:(NSNotification*)notification {
	_isKeyboardHidden = YES;
    [self moveViewForKeyboard:notification up:NO];
}

- (void)moveViewForKeyboard:(NSNotification*)notification up:(BOOL)up {
    NSDictionary *userInfo = [notification userInfo];
    NSTimeInterval animationDuration;
    UIViewAnimationCurve animationCurve;
    CGRect keyboardRect;
	
    [[userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:&animationCurve];
    animationDuration = [[userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    keyboardRect = [[userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
    keyboardRect = [self.view convertRect:keyboardRect fromView:nil];
	
    [UIView beginAnimations:@"ResizeForKeyboard" context:nil];
    [UIView setAnimationDuration:animationDuration];
    [UIView setAnimationCurve:animationCurve];
	
	if (up == YES) {
        CGFloat keyboardHeight = keyboardRect.size.height;
		self.scrollView.frame = CGRectMake(initScrollFrame.origin.x, initScrollFrame.origin.y, initScrollFrame.size.width, initScrollFrame.size.height - keyboardHeight);
	} else {
		// Keyboard is going away (down) - restore original frame
		self.scrollView.frame = initScrollFrame;
    }
	
    [UIView commitAnimations];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    if ([self.textFields containsObject:textField]) {
        [textField resignFirstResponder];
		[self completeTextField:textField];
		return YES;
    } else if (textField == self.contentTextField) {
		UITextField *lastTextField = self.textFields.lastObject;
		if (lastTextField.enabled) [lastTextField becomeFirstResponder];
		else [textField resignFirstResponder];
    }
    return YES;
}

- (IBAction)onAddMorePlaceButtonPressed:(id)sender {
	UITextField *lastTextField = self.textFields.lastObject;
	if (!lastTextField.enabled) {
		[self addPlaceTextField];
	} else if (lastTextField.text != nil && lastTextField.text.length > 0) {
		[self completeTextField:lastTextField];
		[self addPlaceTextField];
	} 
}

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
	XiaoximenSelectPersonViewController *xspvc = segue.destinationViewController;
	
	// record 1: title
	dataSource.partyTitle = contentTextField.text;
	for (UITextField *textField in self.textFields) {
		if (textField.text.length > 0) [dataSource.selectedPlaces addObject:textField.text];
	}
	xspvc.parentDataSource = dataSource;
}
- (IBAction)onBack:(id)sender {
	[self dismissModalViewControllerAnimated:YES];
}
- (void)showSelectTimeViewController
{
	[self performSegueWithIdentifier:@"SelectPersonSegue" sender:self];
}
- (IBAction)onNext:(id)sender {
	
	NSTimeInterval oneDay = 24*60*60;
	NSDate *yesterDay = [NSDate dateWithTimeIntervalSinceNow:-oneDay];
	kal = [[KalViewController alloc] initWithSelectedDate:yesterDay];
	kal.title = @"选择日期以添加";
	UIBarButtonItem *barButtonItem = [[UIBarButtonItem alloc] init];
	barButtonItem.title = @"添加时间";
	kal.navigationItem.backBarButtonItem = barButtonItem;

	kal.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"继续" style:UIBarButtonItemStyleBordered target:self action:@selector(showSelectTimeViewController)];
	dataSource = [[XiaoximenDateDataSource alloc] init];
	dataSource.viewController = kal;
	kal.delegate = dataSource;
	kal.dataSource = dataSource;
#warning Kal Bug: 切换月的时候会Modal
	// Setup the navigation stack and display it.
	[self.navigationController pushViewController:kal animated:YES];
}

@end
